// import moment from "moment";
// import _ from "../../static/jslib/underscore-min.js";
import _ from "underscore";
import moment from "moment";

import Vue from 'vue';
import { logic } from './mixinTaskLogic';
import api from '../api';
import { mapState, mapActions } from 'vuex'
// doTaskEdit,tagAdd,tagDel,tagSet,taskGet,taskAdd,taskSet,taskDel
var titlelast, desclast;

export const taskAndTag = {
  mixins: [logic],
  computed: {
    ...mapState({
      taskDic: state => state.z39.taskDic,
      tagDic: state => state.z39.tagDic,
      taskRunId: state => state.z39.taskRunId,
      taskRunTitle: state => state.z39.taskRunTitle,
      phone: state => state.vux.phone,
      uid: state => state.vux.uid,
      sid: state => state.vux.sid, //websocket id
      socketOpen: state => state.vux.socketOpen, //socket打开状态.
      wsLogin: state => state.vux.wsLogin,
      sortdayDic: state => state.z39.sortdayDic,
      tagsrec: state => state.z39.tagsrec,
    })
  },
  data() {
    return {
      initSystemTags: ["created", "started", "need", "done", "toggle", "cancelled", "due", "used", "usedCalc", "to", "repeat", "critical", "high", "low", "minor"]
    }
  },
  methods: {
    doTaskMend(item1) {
      if (item1.state != "done") return console.log("任务完成后才能重新开启任务修改")
      let tag = this.tagDic[item1.id + "_done"];
      let sdata = { id: item1.id, tagid: tag.id };
      if (!item1.tags.started) sdata.del = true;
      return api.taskMend(sdata).then(data => {
        if (data.errno != 0) return console.log(data.errmsg, 'warning');
        // 删除done标签改成toggle,修改task.state=started, task.tags["toggle"]=moment().format("YYYY-MM-DD HH:mm:ss")
        delete this.tagDic[item1.id + "_done"];
        delete item1.tags["done"];
        if (!sdata.del) {
          this.tagDic[item1.id + "_toggle"] = tag;
          let value = moment().format("YYYY-MM-DD HH:mm:ss");
          Vue.set(item1.tags, "toggle", value);
          item1.state = "started";
        } else {
          item1.state = "";
        }
      })
    },
    doTaskEdit(item1, key, value, opts) { // 只修改 done cancelled toggle   ''
      if (!this.uid) {
        this.$vux && this.$vux.bus && this.$vux.bus.$emit('showlogin', true);
        return Promise.resolve({ errno: 2000, errmsg: "请先登录" });
      }
      console.log("doTaskEdit in");
      if (item1.state == key && value == null) { //如果状态相同则不修改.
        return Promise.resolve({ errno: 2000, errmsg: "数据相同" });
      }
      if (item1.state == "done" && key == "") return this.doTaskMend(item1);
      let item = item1; //this.taskDic[item1.id];
      let realKey = key;
      if (item.state == "toggle" && key == "toggle") { //第二次暂停,是继续状态.
        realKey = "started";
      } else if (key == "") {
        realKey = "toggle";
      }
      let data = { id: item.id, state: realKey };
      let tag;
      item.tags = item.tags || {}; // 如果为空着添加字段;
      if (key == "" || key == "done" || key == "cancelled") { //删除对应冲突的tag 
        if (key == "cancelled" && item.tags["done"] != undefined) {
          tag = this.tagDic[item.id + "_done"]; //item.tags["done"];
        } else if (key == "done" && item.tags["cancelled"] != undefined) {
          tag = this.tagDic[item.id + "_cancelled"]; // item.tags["cancelled"];
        }
        if (tag) {
          this.tagDel(tag, true, item);
        }
      }
      if (key == "") { //如果改为未完成. 就删除完成和取消的标签状态.
        if (item.tags["done"] != undefined) {
          tag = this.tagDic[item.id + "_done"];
          this.tagDel(tag, true, item);
        }
        if (item.tags["cancelled"] != undefined) {
          tag = this.tagDic[item.id + "_cancelled"]; // 
          this.tagDel(tag, true, item);
        }
      }
      let promise, tempProm;
      // if (["due", "need"].indexOf(key) > -1 && ["started", "toggle"].indexOf(item.state) > -1) {
      //如果已经开始执行任务, 修改due或need不修改任务状态. 前期设置任务状态可以更好的看到任务进度.
      if (["done", "cancelled", "toggle", "started", ""].indexOf(key) > -1) {
        promise = this.taskSet(data, item);
      }
      //删除闹铃  mixinTaskLogic.js 中删除任务
      this.deleteClock(item, key);

      if ((key == "done" || realKey == "toggle") && item.tags["started"]) { //计算并添加 used标签.
        let last = item.tags["toggle"] || item.tags["started"];
        let past = moment().diff(last).valueOf();
        let resTime = '';
        if (item.tags["used"]) {
          resTime = this.timeAddCalc(item.tags["used"], this.formatTime2(past));
          console.log("calc:", resTime, item.tags["used"], this.formatTime2(past));
        } else {
          resTime = this.formatTime2(past);
        }
        tempProm = this.doTagSet(item, "used", resTime);
        promise = promise || tempProm;
        if (item.tags["need"] && key == "done") { //计算异动时间
          var nc = getSecond(item.tags.need);
          var uc = getSecond(resTime);
          var tt = uc - nc; //parsetlog
          var abst = Math.abs(tt);
          var diff = abst.formatTime4();
          var timeDiff = tt > 0 ? diff : "-" + diff;
          var diffType = tt > 0 ? "c" : "a"; // c超时 b准时 a提前
          if (abst / nc < 0.15) diffType = "b";
          this.doTagSet(item, "timeDiff", timeDiff + "_" + diffType);
        }
      }
      if (key != "") {
        tempProm = this.doTagSet(item, key, value);
        promise = promise || tempProm;
        var islife = item.tags.life != undefined ? true : false;
        var today = moment().format("YYYY-MM-DD");
        var tempDueTime = item.tags["due"];
        var needSetDue = key == "done" && tempDueTime > today;
        var needAddDue = key == "done" && tempDueTime == undefined;
        var needWeekEndDue = key == "done" && item.tags["weekend"] != undefined && item.tags["due"] == undefined ? true : false;
        // 如果开始时, due没有赋值或者没有具体到时刻,就直接自动赋值当前开始时间.
        var needDefault = key == "started" && isPc && (tempDueTime == undefined || tempDueTime.length < 11) ? true : false;
        if (!islife && (needAddDue || needDefault || needWeekEndDue || needSetDue)) {
          this.doTagSet(item, "due", today).then(data => {
            if (tempDueTime != undefined && value.indexOf(tempDueTime) == -1) { //due不是今日需要提示用户
              this.showNotice("已改为今日", 'success');
            }
          })
          console.log("set due:", tempDueTime, value);
        }
      }
      this.clearClock(item, realKey || key);

      //项目列表拖动 删除标签再添加标签
      var _this = this;
      if (this.projectPart && this.projectPart.some(function(proTag) { return proTag == key; })) {
        if (this.projectPart) {
          this.projectPart.forEach(function(proTag) {
            if (item.tags[proTag] != undefined) {
              _this.tagDel({
                id: _this.tagDic[item.id + '_' + proTag].id,
                key: proTag
              }, true, item);
            }
          })
        }
      }
      console.log("key", key);
      return promise;
    },
    timeAddCalc(time1, time2) { //只有01:10 时分计算,不包含秒.
      let res = 0;
      let t1 = moment.duration(time1).valueOf();
      let t2 = moment.duration(time2).valueOf();
      return this.formatTime2(t1 + t2);
    },
    formatTime(time) {
      time = Math.floor(time / 1000); //毫秒
      // 计算
      var h = 0,
        i = 0,
        s = parseInt(time);
      if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
        if (i > 60) {
          h = parseInt(i / 60);
          i = parseInt(i % 60);
        }
      }
      // 补零
      var zero = function(v) {
        return (v >> 0) < 10 ? "0" + v : v;
      };
      if (h > 0) {
        return [h, zero(i)].join(":");
      } else {
        return i + "m";
      }
    },
    formatTime2(time) {
      time = Math.floor(time / 1000); //毫秒
      // 计算
      var h = 0,
        i = 0,
        s = parseInt(time);
      if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
        //      if (s > 0) { //时间秒向上取整,添加到'分'.
        //        i++;
        //        s = 0;
        //      }
        if (i > 60) {
          h = parseInt(i / 60);
          i = parseInt(i % 60);
        }
      }
      //    else if (s > 0) {
      //      i = 1;
      //      s = 0;
      //    }
      // 补零
      var zero = function(v) {
        return (v >> 0) < 10 ? "0" + v : v;
      };
      // if (h > 0) {
      return [zero(h), zero(i), zero(s)].join(":");
      // } else {
      //   return [zero(i), zero(s)].join(":");
      // }
    },
    usertask() {
      let _this = this;
      this.$vux && this.$vux.bus && this.$vux.bus.$emit('dologin', true);
      return api.usertask().then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        data.type = "z39/usertask";
        var tagDic = {};
        var tasks = data.none.concat(data.today);
        this.$store.commit({ type: "socketOpen", value: true });
        _this.$store.commit(data);
        //_this.$store.commit({ type: "z39/repeat", value: data.repeat });
        _this.$store.commit({ type: "z39/taskToDB", tasks: tasks, act: "add" });
        _this.tagitemsGet();
        try {
          if (!this.wsLogin && this.sid) this.$socket.emit('wsLogin', JSON.stringify({ uid: this.uid, token: api.token }));
          console.info("socket登录", this.wsLogin, this.sid);
        } catch (e) {
          console.error("socket登录错误");
        }
        return Promise.resolve(data);
      })
    },
    doTagSet(item, key, value, show, alertType) {
      if (!this.uid) {
        this.$vux && this.$vux.bus && this.$vux.bus.$emit('showlogin', true);
        return Promise.resolve({ errno: 2000, errmsg: "请先登录" });
      }
      let hide = !show;
      value = value || "";
      item.tags = item.tags || {}; // 如果为空着添加字段;
      let sdata;
      let promise;
      if (item.tags[key] == undefined || key == "toggle") { //添加
        sdata = { taskid: item.id, key: key, value: value };
        promise = this.tagAdd(sdata, hide, item, alertType);
      } else { //修改
        var tagId = this.tagDic[item.id + '_' + key].id;
        sdata = { id: tagId, key: key, value: value };
        promise = this.tagSet(sdata, hide, item, alertType);
      }
      if (key == 'due') {
        this.$store.commit({ type: "z39/daysDic", day: value });
        if (value.length > 15) {
          this.setDueClock(item, value); //mixinTaskLogic.js
          if (!this.phone) {
            if(this.$vux && this.$vux.bus){
				this.$vux.bus.$emit('routeSet', "bind");
				this.$vux.bus.$emit('taskAddVisible', false);
			}
            // this.go("bind");
            this.showNotice("绑定后闹钟生效", 'warn');
          }
        }
      }
      return promise;
      console.log("item.tags", item, item.tags, sdata);
    },
    tagAdd(sdata, hide, item) {
      let _this = this;
      let task = item; // this.taskDic[item.id];   在z39/tagSet也会从字段中获取.
      sdata.value = sdata.value || "";
      sdata.taskid = item.id;
      return api.tagAdd(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        sdata.id = data;
        this.$store.commit({ type: "z39/tagSet", task: task, sdata: sdata });
        if (!hide) {
          this.showNotice("设置成功", 'success');
        }
        return Promise.resolve(data);
      })
    },
    tagsAdd(tagKeyArr, hide, item) { // tagKeyArr=["need","due",...]
      var len = tagKeyArr.length;
      for (var i = 0; i <= len - 1; i++) {
        var key = tagKeyArr[i];
        this.tagAdd({ taskid: item.id, key: key }, hide, item);
      }
    },
    tagsDel(tagKeyArr, hide, item) { // tagKeyArr=["need","due",...]
      var len = tagKeyArr.length;
      var tag;
      for (var i = 0; i <= len - 1; i++) {
        var key = tagKeyArr[i];
        tag = this.tagDic[item.id + "_" + key];
        this.tagDel(tag, hide, item);
        if (key == "due") this.clearClock(item, 2);
      }
    },
    tagDel(tag, hide, item) {
      let _this = this;
      return api.tagDel({ id: tag.id, key: tag.key }).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        Vue.delete(item.tags, tag.key);
        if (!hide) {
          this.showNotice("标签删除成功", 'success');
        }
        return Promise.resolve(data);
      })
    },
    tagSet(sdata, hide, item, alertType) {
      let _this = this;
      let task = item; //this.taskDic[item.id];
      sdata.value = sdata.value || "";
      return api.tagSet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        this.$store.commit({ type: "z39/tagSet", task: task, sdata: sdata });
        if (!hide) {
          this.showNotice("设置成功", 'success');
          if (alertType == 'notify') {
            _this.$notify({
              title: '成功',
              message: '设置成功',
              type: 'success'
            });
          }
        }
        return Promise.resolve(data);
      })
    },
    tasksAdd(sdata) {
      return api.tasksAdd(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        this.showNotice("添加成功,需要刷新查看", 'success');
        return Promise.resolve(data);
      })
    },
    taskGet(id) { //接口在任务详情中会需要.
      return api.taskGet({ id: id }).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        let tasks = data.tasks || [];
        // delete data.tasks ;
        let temp = [data].concat(tasks);
        this.$store.commit({ type: "z39/taskToDB", tasks: temp, act: "add" });
        this.$store.commit({ type: "z39/taskDetail", task: this.taskDic[id] });
        return Promise.resolve(data);
      })
    },
    taskAdd(sdata, tags, notAdd) { //notAdd 不自动添加uid
      sdata.title = sdata.title.trim();
      if (_.isEmpty(sdata.title)) {
        this.showNotice("请输入标题", 'warn');
        return Promise.reject("title null");
      }
      if (sdata.title == titlelast && sdata.desc == desclast) {
        this.showNotice("不能创建相同任务", 'warn');
        return Promise.reject({ errno: 3, errmsg: "不能创建相同任务" });
      }
      titlelast = sdata.title;
      desclast = sdata.desc;
      let _this = this;
      let tempTask;
      if (tags != undefined && tags != null) {
        sdata.tags = tags;
      }
      return api.taskAdd(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        data.state = data.state || "";
        data.desc = data.desc || "";
        if (data.uid_auto != undefined) {
          delete data.uid_auto;
        }
        if (data.token != undefined) {
          delete data.token;
        }
        if (sdata.tags && sdata.tags["due"] && sdata.tags["due"].length >= 10) {
          this.$store.commit({ type: "z39/daysDic", day: sdata.tags["due"] });
        }
        this.$store.commit({ type: "z39/taskToDB", tasks: [data], act: "add" });
        // _this.resetInput();
        this.showNotice("添加成功", 'success');
        return Promise.resolve(data);
      })
    },
    taskSet(sdata, task) {
      // console.log("taskset in");
      let _this = this;
      return api.taskSet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误", errno: 1001 };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        if (_.isEmpty() || this.taskRunId == task.id) {
          let taskRun;
          let notRun = ["done", "cancelled", "toggle", ""];
          if (sdata.state == "started") {
            taskRun = { taskRunTitle: task.title, taskRunId: task.id };
          } else if (notRun.indexOf(sdata.state) != -1) {
            taskRun = { taskRunTitle: "", taskRunId: 0 };
          }
          this.$store.commit(Object.assign({ type: "z39/taskRun" }, taskRun));
        }
        data = data.data;
        // if (sdata.tags) {
        this.$store.commit(Object.assign({ type: "z39/taskSet" }, sdata, { task: task }));
        // }
        // if (task != null) {
        //   if (sdata.title && sdata.title != task.title) Vue.set(task, "title", sdata.title); // task.title = sdata.title;
        //   if (sdata.pid && sdata.pid != task.pid) Vue.set(task, "pid", sdata.pid); // task.pid = sdata.pid;
        //   if (sdata.desc && sdata.desc != task.desc) Vue.set(task, "desc", sdata.desc); // task.desc = sdata.desc;
        //   if (sdata.state && sdata.state != task.state) Vue.set(task, "state", sdata.state); // task.state = sdata.state;
        //   if (sdata.uid && sdata.uid != task.uid) Vue.set(task, "uid", sdata.uid); // task.uid = sdata.uid;
        // }
        this.showNotice("修改成功", 'success');
        return Promise.resolve(data);
      })
    },
    taskDel(id) {
      let _this = this;
      return api.taskDel({ id: id }).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/taskToDB", tasks: [{ id: id }], act: "del" });
        this.showNotice("任务取消成功", 'success');
        return Promise.resolve(data);
      })
    },
    tasksGet(sdata) {
      let _this = this;
      return api.tasksGet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        let tasks = data.tasks.concat(data.likes || []);
        _this.$store.commit({ type: "z39/taskToDB", tasks: tasks, act: "add" });
        return Promise.resolve(data);
      })
    },
    tagitemsGet() {
      let _this = this;
      return api.tagitemsGet({}).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/tagitems", tagitems: data });
        return Promise.resolve(data);
      })
    },
    projectsGet(sdata) {
      let _this = this;
      return api.projectsGet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        return Promise.resolve(data);
      })
    },
    projectGet(sdata) {
      let _this = this;
      return api.projectGet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/taskToDB", tasks: data.tasks, act: "add", override: true });
        return Promise.resolve(data);
      });
    },
    showNotice(msg, type, isPcNotUse) {
      //直接在index.html写变量 var isPc = false; 
      type = type || "success";
      if (!isPc) { //手机版
        if (type == "warning") type = "warn";
        this.$vux.toast.show({ text: msg, type: type })
      } else {
        if (type == "warn") type = "warning";
        console.log(type)
        this.$message({ message: msg, type: type });
      }
    },
    projectAdd(sdata) {
      let _this = this;
      return api.projectAdd(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        sdata.id = data;
        sdata.gid = data;
        _this.$store.commit({ type: "z39/projectAdd", project: sdata });
        _this.showNotice("添加成功", 'success');
        return Promise.resolve(data);
      })
    },
    projectSet(sdata) {
      let _this = this;
      return api.projectSet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/projectSet", project: sdata });
        _this.showNotice("修改成功", 'success');
        return Promise.resolve(data);
      })
    },
    projectDel(id) {
      let _this = this;
      return api.projectDel({ id: id }).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/projectDel", id: id });
        _this.showNotice("删除成功", 'success');
        return Promise.resolve(data);
      })
    },
    repeatAdd(sdata, hide) {
      let _this = this;
      return api.repeatAdd(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          if (!hide) _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        sdata.id = data;
        if (!hide) _this.showNotice("添加成功", 'success');
        return Promise.resolve(data);
      })
    },
    repeatSet(sdata) {
      return api.repeatSet(sdata).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        this.showNotice("设置成功", 'success');
        return Promise.resolve(data);
      })
    },
    repeatDel(id) {
      let _this = this;
      return api.repeatDel({ id: id }).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          _this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.showNotice("取消重复", 'success');
        return Promise.resolve(data);
      })
    },
    getTasksList: function(params) {
      return api.sortdayGet(params).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn', true);
          return Promise.reject(data.errmsg);
        }
        var days, sortStr = data.data.sorts;
        if (sortStr != undefined) days = [{ day: params.day, sorts: sortStr }]; //单日
        else if (data.data.sortsArr) days = data.data.sortsArr;
        if (days) this.$store.commit({ type: "z39/sortdayDic", sorts: days });
        var taskList = data.data.tasks;
        this.$store.commit({
          type: "z39/taskToDB",
          tasks: taskList,
          act: "add"
        });
        return Promise.resolve(data.data);
      })
    },
    sortdataAdd(sdata) {
      api.sortdayAdd(sdata).then(data => {
        if (data.errno != 0) return this.showNotice("设置失败", 'warn');
        var days = [{ day: sdata.day, sorts: sdata.sorts }]; //单日
        this.$store.commit({ type: "z39/sortdayDic", sorts: days });
      })
    },
    getSortTask(list, day) {
      var sortStr = this.sortdayDic[day];
      if (!sortStr || sortStr.length == 0) return list;
      var res = [];
      let sortArr = sortStr.split(",");
      var len = sortArr.length;
      var sortDic = {};
      for (var i = 0; i <= len - 1; i++) {
        var id = sortArr[i];
        sortDic["id" + id] = i;
      }
      for (var j = list.length - 1; j >= 0; j--) {
        var task = list[j];
        var tempi = sortDic["id" + task.id];
        if (tempi != undefined) {
          res[tempi] = list.splice(j, 1)[0];
        }
      };
      res = res.concat(list);
      res = _.compact(res);
      return res;
    },
    //标签模板添加
    addTagTmp: function(tagItem) {
      //评估重复调用这个接口，负责人to先不做，其他和开发用弹窗的方法
      if (this.addCardItemLoading) {
        return Promise.reject("loading");
      };
      if (!this.addCardItemTitle) {
        this.showNotice('请输入标题', 'warn', true);
        return Promise.reject("miss title");
      }

      var titleText = this.addCardItemTitle.trim();
      //如果添加的标签是need,要做时间格式化 1:30
      if (tagItem.key == 'need') {
        var reg = /^\d$/ig;
        if (!reg.test(titleText)) {
          this.showNotice('格式输入有误，必须是纯数字', 'warn', true);
          return Promise.reject("miss title");
        } else if (titleText > 1440) {
          this.showNotice('输入的值需小于1440', 'warn', true);
          return Promise.reject("miss title");
        } else {
          titleText = parseInt(titleText / 60) + ':' + (titleText % 60)
        }
      }
      this.addCardItemLoading = true;
      var params = {
        id: tagItem.id,
        pid: null,
        count: null,
        type: 1,
        name: tagItem.name,
        key: tagItem.key,
        tmp: tagItem.key + '=' + titleText + ',' + tagItem.tmp
        //      tmp: tagItem.key//+',' + tagItem.tmp
      }
      if (tagItem.init == 1) {
        return api.tagTmpAdd(params).then(data => {
          this.addCardItemLoading = false;
          if (data == undefined || data.errno != 0) {
            if (data == undefined) data = { errmsg: "网络错误" };
            this.showNotice(data.errmsg, 'warn', true);
            return Promise.reject(data.errmsg);
          }
          this.addCardItemTitle = '';
          this.showNotice('保存成功', 'success', true);
          this.$store.commit({ type: "z39/updateTagTmps", id: data.data, tmp: params.tmp, key: tagItem.key });
          return Promise.resolve(data.data);
        })
      } else {
        return api.tagTmpPut(params).then(data => {
          this.addCardItemLoading = false;
          if (data == undefined || data.errno != 0) {
            if (data == undefined) data = { errmsg: "网络错误" };
            this.showNotice(data.errmsg, 'warn', true);
            return Promise.reject(data.errmsg);
          }
          this.addCardItemTitle = ''
          this.showNotice('保存成功', 'success', true);
          this.$store.commit({ type: "z39/updateTagTmps", id: params.id, tmp: params.tmp, key: tagItem.key });
          return Promise.resolve(data.data);
        })
      }
    },
    sortdayGet(day) {
      return api.sortdayGet({ day }).then(data => {
        if (data == undefined || data.errno != 0) {
          if (data == undefined) data = { errmsg: "网络错误" };
          this.showNotice(data.errmsg, 'warn');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        // this.sortStr = data.sorts ;
        this.$store.commit({ type: "z39/taskToDB", tasks: data.tasks, act: "add" });
        console.log(data);
        return Promise.resolve(data);
      })
    },
    deleteClock(task, key) { // 检查和删除闹铃    
      // var key = task.state;
      if (["done", "cancelled", "toggle"].indexOf(key) == -1) return;
      var clockKey = "clock_" + task.id;
      var clockKey1 = "clock1_" + task.id;
      var oldClock = localStorage.getItem(clockKey);
      var oldClock1 = localStorage.getItem(clockKey1);
      if (oldClock) api.clockDel({ key: oldClock }).then((data) => {
        localStorage.removeItem(clockKey)
      });
      if (oldClock1) api.clockDel({ key: oldClock1 }).then((data) => {
        localStorage.removeItem(clockKey1)
      });
    },
    getRepeat(all, sday) { //从后端重复表中的数据获取执行日期的任务.
      let res = [];
      let day = moment(sday).format('D');
      let month = moment(sday).format('M');
      let daytime = moment(sday).format('MM-DD');
      let week = moment(sday).isoWeekday();

      let part2, temp;
      var len = all.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = all[i];
        if (item.rule == 'D') { //每天
          res.push(item);
        } else if (item.rule == 'M') { //每月
          if (day == moment(item.time_rule).format('D')) res.push(item);
        } else if (item.rule == 'Y') { //每年
          if (daytime == moment(item.time_rule).format('MM-DD')) res.push(item);
        } else if (item.rule == "W") { //每周
          if (week == moment(item.time_rule).isoWeekday()) res.push(item);
        } else if (item.rule.charAt(0) == "W" && item.rule.length > 1) { //周几
          part2 = item.rule.charAt(1); //数值是1-7
          if (week == part2) res.push(item);
        } else if (item.rule.charAt(0) == "D") {
          temp = item.rule.split(",");
          if (temp.length == 1) { //只有1天.
            part2 = item.rule.substr(1);
            if (part2 == day) res.push(item);
          } else {
            temp.forEach(dayItem => {
              part2 = dayItem.substr(1);
              if (part2 == day) return res.push(item);
            })
          }
        }
      }
      return res;
    },
    getTagsrec() {
      if (this.tagsrec.length > 0) return Promise.resolve(this.tagsrec);
      return api.tagsrec().then(data => {
        if (data.errno != 0) return Promise.resolve(data);
        data = data.data;
        this.$store.commit(Object.assign({ type: "z39/addTagsres" }, { tags: data }));
        return Promise.resolve(data);
      })
    },
  }

}
